/**
 *
 * @class app.widgets.TimeSheet
 * @extends Ext.Panel
 */

Ext.ns('app.widgets'); 

app.widgets.TimeSheet = Ext.extend(Ext.Panel, {
 
	/*
	 * Soft config: 
	 */
	
    border:false

    /*
     * Init functions: 
     */
    
    ,initComponent:function() {
    	
        var config = this.createConfig();

        Ext.apply(this, config);
        Ext.apply(this.initialConfig, config);

        app.widgets.TimeSheet.superclass.initComponent.apply(this, arguments);
        
        this.initListeners(); 
    } 

	, initListeners : function(){}
	
	/*
     * Factory Functions:
     */
    
    , createConfig : function(){
    	
    	// define a custom summary function
        Ext.ux.grid.GroupSummary.Calculations['totalLength'] = this.calcTotalLength; 

    	
    	this.grid = this.createGrid();
    	this.totalPanel = this.createTotalPanel(); 
    	
    	var config = {
			
			layout : 'anchor' 
			, iconCls : 'timesheet-icon' 
			
			, layoutConfig : {
				padding : '0 5 5'
			}
			
			, items : [this.grid, this.totalPanel] 
    	};
    	
    	return config; 
    	
    }
    
    , createGrid : function(){
    	
    	var store = new Ext.data.GroupingStore({
    		
    		reader: new Ext.data.JsonReader({
				totalProperty: 'results',
				//id: 'id', 
				fields: [
				         'task',
				         'time_length',
				         {name: 'start', type: 'date', dateFormat: app.Utils.DateFormat.W3C},
				         {name: 'stop', type: 'date', dateFormat: app.Utils.DateFormat.W3C},
				         ]
			})
		
			, proxy: new Ext.data.DirectProxy({
				directFn: TimeSheet.load
			})
    	
    		, groupField: 'task'
    		
    	}); 
    	
    	var toolbar = new Ext.Toolbar({
    		items : [
    		         {iconCls:'refresh-icon',scope:this,handler:this.onRefresh}, '-'
    		         , {iconCls:'collapse-icon',scope:this,handler:this.onCollapse}
    		         , {iconCls:'expand-icon',scope:this,handler:this.onExpand}
    		         ]
    	}); 
    	
    	var csm = new Ext.grid.CheckboxSelectionModel(); 
    	
    	var taskId = Ext.id(); 
    	
    	return new Ext.grid.GridPanel({
    		border: false, 
    		anchor: '100% 100%',
    		store: store, 
    		tbar: toolbar, 
    		stripeRows: true, 
//    		autoExpandColumn: taskId, 
    		sm : csm, 
    		view: new Ext.grid.GroupingView(), 
    		plugins: [new Ext.ux.grid.GroupSummary()], 
    		loadMask: true, 
    		columns : [csm 
    		           , {id: taskId, dataIndex:'task', header: 'Task', renderer: this.renderTask, hidden:true}
    		           , {
    		        	   dataIndex:'start', 
    		        	   header:'Start', 
    		        	   renderer: this.renderEvent, 
    		        	   width: 200 
//    		        	   , css:'background-color: #d1d1d1;'
    		           }, {
    		        	   dataIndex:'stop', 
    		        	   header:'Stop', 
    		        	   renderer: this.renderEvent, 
    		        	   width: 200 
//    		        	   , css:'background-color: #e6e6e6;'
    		           }, {
							dataIndex : 'time_length',
							header : 'Time Elapsed',
							renderer : this.renderLength,
							width : 150, 
							summaryType: 'totalLength', 
							summaryRenderer: this.renderLengthSum
    		           }] 
    		
    	}); 
    	
    }
    
    , createTotalPanel : function(){
    	return {xtype: 'panel', html: '<h1>Time Statistics</h1>',anchor:'0% 100%'}; 
    }

    /*
	 * Event Handlers:
	 */

    , onRender : function() {
    	app.widgets.TimeSheet.superclass.onRender.apply(this, arguments);
    	
    	this.grid.store.load({
    		
    		callback : function(){
    			this.grid.view.collapseAllGroups()
    		} 
    		
    		, scope : this
    		
    	}); 
    }
    
    , onRefresh : function(){
    	this.grid.store.load(); 
    }
    
    , onCollapse : function(){
    	this.grid.view.collapseAllGroups();  
    }
    
    , onExpand : function(){
    	this.grid.view.expandAllGroups();  
    }
    
    , onShow : function(){
    	this.grid.store.load();
    	app.widgets.TimeSheet.superclass.onShow.apply(this, arguments);
    }
    
    /*
     * Renderers: 
     */
    
    , renderLength : function(length){
    	var output = ''; 
    	
    	if (length){
	    	for ( var unit in length) {
				if(!Ext.isFunction(length[unit])){
					output += unit + ': <b><i>' + length[unit] + '</i></b>, ';
				} 
			}
	    	
	    	output = output.substring(0, output.length - 2);
	    	
	    	output += (output != '') ? '.' : 'less than a minute.';   
    	}
    	
    	return output; 
    }
    
    , renderEvent : function(eventDateTime){
    	var format; 
    	var today = new Date().getDate(); 
    	var yesterday = today - 1; 
    	
    	if(eventDateTime){
	    	if ( eventDateTime.getDate() == today || 
	    			eventDateTime.getDate() == yesterday) {
	    		format = app.Utils.DateFormat.TIME;
	    	} else {
	    		format = app.Utils.DateFormat.FULL;
	    	}
	    	
	    	var event = Ext.util.Format.date(eventDateTime, format);  
	    	return !(eventDateTime.getDate() == yesterday) ? event : 'yesterday ' + event;
    	}
    	
    	return ''; 
    }
    
    , renderTask : function(taskName){
    	return '<span class="task-name">' + taskName + '</span>'; 
    }
    
    , renderLengthSum : function(length){
    	var output = '<h1>Total time: </h1>'; 
    	
    	if (length){
	    	for ( var unit in length) {
				if(!Ext.isFunction(length[unit])){
					output += unit + ': <b><i>' + length[unit] + '</i></b>, ';
				} 
			}
	    	
	    	output = output.substring(0, output.length - 2);
	    	
	    	output += (output != '') ? '.' : 'less than a minute.';   
    	}
    	
    	return '<span class="length-sum">' + output + '</span>'; 
    } 
 
    /*
     * Utility functions: 
     */
    
    , calcTotalLength : function(totalLength, record, field){
        var oLength = record.data.time_length;

        if (oLength){
        	
        	if (totalLength === 0){
            	totalLength = new Array(); 
        	}
        	
	        for (var unit in oLength){
	        	if(!Ext.isFunction(oLength[unit])) {
		    		if(totalLength[unit]){
		    			totalLength[unit] += oLength[unit]; 
		    		} else {
		    			totalLength[unit] = oLength[unit];
		    		}
	        	}
	    	}
	        
        }
        
    	return totalLength;
    }
    
}); 
 

Ext.reg('timesheet', app.widgets.TimeSheet); 